package 中等;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class 合并区间 {

    public static void main(String[] args) {
        int[][] intervals = {{1,3},{2,6},{8,10},{15,18},{5,7}};
        int[][] merge = merge(intervals);
        for (int[] ints : merge) {
            System.out.println(Arrays.toString(ints));
        }
    }

    public static int[][] merge(int[][] intervals) {
        List<int[]> list = new ArrayList<>();
        Arrays.sort(intervals,(a,b)->{
            return a[0]-b[0];
        });
        int right = intervals[0][1];
        int left  = intervals[0][0];
        for (int i = 1; i < intervals.length; i++) {
            if (right>intervals[i][1]){

            }else if (intervals[i][0]<=right){
                right = intervals[i][1];
            }else {
                list.add(new int[]{left,right});
                left = intervals[i][0];
                right = intervals[i][1];
            }
        }
        list.add(new int[]{left,right});


        return list.toArray(new int[list.size()][]);

    }
}
